package sendmail;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class AuthenticateFilter implements Filter {
	private static final Logger log = Logger.getLogger(AuthenticateFilter.class
			.getName());

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest r1, ServletResponse r2,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) r1;
		HttpServletResponse resp = (HttpServletResponse) r2;
		UserService service = UserServiceFactory.getUserService();
		String requestURI = req.getRequestURI();
		if (!service.isUserLoggedIn()) {
			String loginURL = service.createLoginURL(requestURI);
			resp.sendRedirect(loginURL);
		} else if (!service.isUserAdmin()) {
			resp.sendRedirect("/");
		} else {
			chain.doFilter(req, resp);
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
